﻿namespace IntellectShop.Web2.Hardware.Controllers
{
	using System;
	using System.Collections.Generic;
	using System.IO;
	using System.Text;
	using System.Web;
	using System.Web.Mvc;
	using System.Xml;
	using IntellectShop.Common;
	using IntellectShop.Web2.Hardware.ViewModels;

	[IntellectShop.Web2.Hardware.Code.NoCache]
	[IntellectShop.Web2.Hardware.Code.HandleErrorWithELMAH]
	[ValidateInputAttribute(false)]
	public class SoftwareController : Controller
	{
		public ActionResult Browse(string categoryID)
		{
			int id = Int32.Parse(categoryID);
			var viewModel = new CategoryBrowseSoftwareViewModel
			{
				Category = Common.Category.RetrieveByID(id),
				Softwares = Common.Software.RetrieveByCategoryID(id)
			};

			return View(viewModel);
		}

		public ActionResult CategoryIndex()
		{
			List<Common.Category> categories = Common.Software.RetrieveCategoriesAll();

			var viewModel = new StoreCategoryIndexViewModel
			{
				NumberOfCategories = categories.Count,
				Categories = categories
			};

			return View(viewModel);
		}

		public ActionResult Details(int id)
		{
			var soft = Common.Software.RetrieveByCommodityID(id);
			if (soft == null)
				throw new HttpException(404, "Page not found");

			return View(soft);
		}

		public ActionResult Index()
		{
			var viewModel = new SoftwareIndexViewModel
			{
				Softwares = Common.Software.RetrieveAll()
			};

			return View(viewModel);
		}

		[Authorize(Roles = Globals.AdministratorRoleName)]
		public ActionResult Create()
		{
			var viewModel = new SoftwareEditViewModel
			{
				Categories = Common.Category.RetrieveAll(),
				Software = new Common.Software()
			};

			return View(viewModel);
		}

		[Authorize(Roles = Globals.AdministratorRoleName)]
		[HttpPost]
		public ActionResult Create(Common.Software software)
		{
			try
			{
				if (!ModelState.IsValid)
					throw new ArgumentException("Ошибка при заполнении полей для: Software!");

				software.Create(HttpContext.User.Identity.Name);
				return RedirectToAction("Index");
			}
			catch (Exception e)
			{
				var viewModel = new SoftwareEditViewModel
				{
					Categories = Common.Category.RetrieveAll(),
					Software = software,
					Message = e.Message
				};

				return View(viewModel);
			}
		}

		[Authorize(Roles = Globals.AdministratorRoleName)]
		public ActionResult Edit(int id)
		{
			var viewModel = new SoftwareEditViewModel
			{
				Categories = Common.Category.RetrieveAll(),
				Software = Common.Software.RetrieveByCommodityID(id)
			};

			return View(viewModel);
		}

		[Authorize(Roles = Globals.AdministratorRoleName)]
		[HttpPost]
		public ActionResult Edit(int id, FormCollection collection)
		{
			var software = Common.Software.RetrieveByCommodityID(id);
			try
			{
				if (!ModelState.IsValid)
					throw new ArgumentException("Ошибка при заполнении полей для: Software!");

				UpdateModel(software, "Software");
				software.Update(HttpContext.User.Identity.Name);
				return Redirect(Url.RouteUrl(new { action = "Index" }) + "#id" + id);
			}
			catch (Exception e)
			{
				var viewModel = new SoftwareEditViewModel
				{
					Software = Common.Software.RetrieveByCommodityID(id),
					Categories = Common.Category.RetrieveAll(),
					Message = e.Message
				};

				return View(viewModel);
			}
		}

		[Authorize(Roles = Globals.AdministratorRoleName)]
		public ActionResult Delete(int softwareID)
		{
			var viewModel = new SoftwareRemoveViewModel()
			{
				Software = Common.Software.RetrieveBySoftwareID(softwareID)
			};

			return View(viewModel);
		}

		[Authorize(Roles = Globals.AdministratorRoleName)]
		[HttpPost]
		public ActionResult Delete(int softwareID, FormCollection collection)
		{
			try
			{
				if (!ModelState.IsValid)
					throw new ArgumentException("Ошибка при заполнении полей для: Software!");

				Common.Software.Delete(softwareID);
				return RedirectToAction("Index");
			}
			catch (Exception e)
			{
				var viewModel = new SoftwareRemoveViewModel()
				{
					Software = Common.Software.RetrieveBySoftwareID(softwareID),
					Message = e.Message
				};

				return View(viewModel);
			}
		}

		[Authorize(Roles = Globals.AdministratorRoleName)]
		[AcceptVerbs(HttpVerbs.Get)]
		public ActionResult ExportXml()
		{
			string filename = "Softwares.xml";
			string contentDisposition = String.Format("attachment; filename={0};", filename);

			Response.Clear();
			Response.ContentType = "application/xml";
			Response.AppendHeader("Content-Disposition", contentDisposition);

			XmlDocument doc = IntellectShop.Common.Software.ExportToXml();
			using (MemoryStream outStream = new MemoryStream())
			{
				using (XmlTextWriter writer = new XmlTextWriter(outStream, Encoding.UTF8))
				{
					writer.Formatting = Formatting.Indented;
					writer.Indentation = 1;
					writer.IndentChar = '\t';
					doc.Save(writer);

					return File(outStream.ToArray(), "application/xml");
				}
			}
		}
	}
}
